package com.qf.dao.impl;

import com.qf.dao.ProductDao;
import com.qf.pojo.Product;
import com.qf.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 *
 * 商品数据访问接口实现
 */
public class ProductDaoImpl implements ProductDao {
    /**
     * 查询首页最新商品
     * @return 返回商品列表
     */
    @Override
    public List<Product> selectNewProdcuts() throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;

        //sql
        //按照字典pdate 降序排序
        String sql = "SELECT * FROM product ORDER BY pdate DESC  LIMIT 9 ;" ;

        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }

    /**
     * 查询首页热门商品
     * @return
     * @throws SQLException
     */
    @Override
    public List<Product> selectHotProducts() throws SQLException {

        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;

        //sql
        //按照条件 is_hot
        String sql = "SELECT * FROM product where is_hot= 1  LIMIT 9 ;" ;

        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }
    /**
     * 查询商品实体根据商品id
     * @param pid 商品编号
     * @return 返回商品实体
     */
    @Override
    public Product selectProductByPid(String pid) throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        //sql
        String sql= "select * from product where pid =?";
        Product product = qr.query(sql,new BeanHandler<Product>(Product.class),pid);

        return product;
    }
    /**
     *  数据接口分页查询商品类别
     * @param currentPage 当前页码
     * @param pageSize 每页条数
     * @param cid 分类id
     * @return 返回商品列表
     */
    @Override
    public List<Product> selectProductByPage(int currentPage, int pageSize, String cid) throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        //sql
        String sql ="select *from product where cid = ? limit =?,?";
        List<Product> list = qr.query(sql,new BeanListHandler<Product>(Product.class),
                cid,
                (currentPage - 1) * pageSize,pageSize);
        return list;
    }
    /**
     * 获取指定商品分类的总记录数
     * @param cid 分类id
     * @return 返回总记录数
     */
    @Override
    public int selectTotalCountByProduct(String cid) throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        //sql
        String sql = "select count(pid) from product where cid = ? ";
        Object obj = qr.query(sql,new ScalarHandler<>(),cid);
        String s = String.valueOf(obj);
        int totalCount = Integer.parseInt(s);
        return totalCount;
    }
}
